<template>
  <div class="container">
    <div>
      <div class="btn_container">
        <el-button
          type="primary"
          @click="handleAddBrowser('a')"
          :loading="loadingA"
          >笔记上号</el-button
        >
        <el-button @click="handleAddBrowser('b')" :loading="loadingB"
          >创作者上号</el-button
        >
        <div class="refreshBtn" @click="handleRefresh">
          <el-icon>
            <Refresh />
          </el-icon>
        </div>
      </div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="账号名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入账号名称"
            style="width: 240px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="ID	" />
      <!-- <el-table-column prop="ads_power_id" label="浏览器id	" /> -->
      <el-table-column prop="avatar" label="头像" header-align="center">
        <template #default="scoped">
          <el-image :src="scoped.row.avatar" style="width: 50px" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="用户名	" />
      <el-table-column prop="number" label="红薯号" />
      <el-table-column prop="note" label="备注" />
      <el-table-column prop="note_status" label="笔记cookie状态" width="155" />
      <el-table-column
        prop="creator_status"
        label="创作者cookie状态"
        width="155"
      />
      <!-- <el-table-column prop="unique_tag" label="浏览器唯一标识" width="155" /> -->
      <el-table-column prop="update_time" label="更新时间">
        <template #default="scoped">
          {{
            scoped.row.update_time
              ? moment(scoped.row.update_time).format("YYYY-MM-DD")
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="operate"
        label="操作"
        width="120"
        align="center"
        fixed="right"
      >
        <template #default="scoped">
          <el-dropdown @command="(e) => handleOperate(e, scoped.row)">
            <el-button class="videoDrown">
              操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="update">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
                <el-dropdown-item command="note">笔记上号</el-dropdown-item>
                <el-dropdown-item command="publish"
                  >创作者上号</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_container">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="page_size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog v-model="deleteShow" title="提示" width="400">
      确定删除此内容
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteShow = false">取消</el-button>
          <el-button type="primary" @click="handDelete"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editShow"
      title="编辑"
      width="500"
      center
      @close="resetForm"
    >
      <el-form :model="updateForm" label-width="100px" ref="updateFormRef">
        <el-form-item label="备注" class="model-item" prop="declarationElement">
          <el-input
            v-model="updateForm.note"
            placeholder="请输入备注"
            clearable
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editShow = false">取消</el-button>
          <el-button type="primary" @click="handUpdate"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, watch } from "vue";
import {
  xhs_list,
  get_ads,
  ads_update,
  user_create,
  user_delete,
  user_update,
} from "../api/xhs.js";
import { ElMessage } from "element-plus";
import { Refresh, ArrowDown } from "@element-plus/icons-vue";
import moment from "moment";
import { userStore } from "@/store/user";
const user = userStore();
const page_size = ref(10);
const page = ref(1);
const total = ref(0);
const tableData = ref([]);
const formInline = reactive({
  note: "",
});
const deleteShow = ref(false);
const selectedItem = ref({});
const editShow = ref(false);
const updateForm = reactive({ note: "" });
const updateFormRef = ref(null);
const loadingA = ref(false); // 笔记上号按钮的加载状态
const loadingB = ref(false); // 创作者上号按钮的加载状态
// 重置模态框的form表单
const resetForm = () => {
  if (updateFormRef.value) {
    updateFormRef.value.resetFields();
  }
  Object.assign(updateForm, {
    note: "",
  });
};
const handleOperate = (e, item) => {
  selectedItem.value = item;
  switch (e) {
    case "delete":
      deleteShow.value = true;
      break;
    case "update":
      editShow.value = true;
      break;
    case "note":
      handleSingleBrowser("a", item);
      break;
    case "publish":
      handleSingleBrowser("b", item);
      break;
  }
};
const handleSearch = () => {
  const { name } = formInline;
  const params = {
    name,
  };
  getList(params);
};
// 删除环境
const handleDelAds = async (id) => {
  const delete_result = await window.electronAPI.fetch(
    `http://local.adspower.net:50325/api/v1/user/delete`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ user_ids: [id] }),
    }
  );
  if (delete_result.code !== 0) {
    ElMessage.error(delete_result.msg);
  }
};
// 启动浏览器
const openBrowser = async (
  response_result,
  headless,
  is_new,
  unique_tag,
  key
) => {
  const ads_power_id = is_new ? response_result.data.id : response_result;
  console.log("执行打开浏览器", new Date().getTime(), ads_power_id);
  const start_result = await window.electronAPI.fetch(
    `http://local.adspower.net:50325/api/v1/browser/start?user_id=${encodeURIComponent(
      ads_power_id
    )}&ip_tab=0&open_tabs=1&headless=${headless}`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
  console.log("成功打开浏览器", new Date().getTime());
  console.log("start_result", start_result);
  if (!start_result.data) {
    ElMessage.error(start_result.msg);
    return;
  }
  await ads_update({
    ads_power_id,
    unique_tag,
  });
  const { ws, webdriver } = start_result.data;
  const args = isWindows()
    ? [`"${ws.selenium}"`, `"${webdriver}"`, `'${user.$state.userInfo.token}'`]
    : [`'${ws.selenium}'`, `'${webdriver}'`, `'${user.$state.userInfo.token}'`];
  const pythons = localStorage.getItem("pythons")
    ? JSON.parse(localStorage.getItem("pythons"))
    : {};
  const downloadUrl = pythons[key];
  console.log("downloadUrl", downloadUrl);
  console.log("执行note_login脚本开始", new Date().getTime());
  const name = downloadUrl.split("/").pop();
  console.log("执行命令", `${downloadUrl} ${args.join(" ")}`);
  const result = await window.electronAPI.downloadAndExecute(
    downloadUrl,
    args,
    `${key}_${name}`
  );
  console.log("note_login_result", result);
  console.log("执行note_login脚本结束", new Date().getTime());
  if (!result) return;
  const new_result = JSON.parse(result);
  // 如果是创作者上号
  const types = ["b", "b_win"];
  if (new_result.code === 0) {
    const type = types.includes(key) ? 1 : undefined;
    await user_create({ unique_tag, type, ...new_result.data });
    await ads_update({
      ads_power_id,
      unique_tag,
    });
    const stop_result = await window.electronAPI.fetch(
      `http://local.adspower.net:50325/api/v1/browser/stop?user_id=${encodeURIComponent(
        ads_power_id
      )}&ip_tab=0&open_tabs=1&headless=${headless}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    if (stop_result.code === 0) {
      ElMessage.success("添加成功");
      await getList();
    } else {
      ElMessage.error(stop_result.msg);
    }
  } else {
    ElMessage.error(new_result.msg);
  }
};
const handleAddBrowser = async (python_key) => {
  const exact_key = isWindows() ? "_win" : "";
  try {
    if (python_key === "a") {
      loadingA.value = true;
    }
    if (python_key === "b") {
      loadingB.value = true;
    }
    const res = await get_ads();
    if (res.code === 0) {
      console.log("ads_data", res.data);
      const { unique_tag, is_new, ads_power_id } = res.data;
      // 判断是否是新的浏览器
      if (is_new) {
        // 查询分组
        const xhs_result = await window.electronAPI.fetch(
          `http://local.adspower.net:50325/api/v1/group/list?group_name=${encodeURIComponent(
            "小红书"
          )}`,
          {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
        console.log("33232", xhs_result);
        let group_id;
        if (
          xhs_result.data &&
          xhs_result.data.list &&
          xhs_result.data.list.length > 0
        ) {
          group_id = xhs_result.data.list[0].group_id;
        } else {
          // 若不存在分组则新建分组
          const create_result = await window.electronAPI.fetch(
            `http://local.adspower.net:50325/api/v1/group/create`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({ group_name: "小红书" }),
            }
          );

          if (create_result.data && create_result.data.group_id) {
            group_id = create_result.data.group_id;
          }
        }
        // 如果不存在分组则停止新建
        if (!group_id) return;
        // 创建新的浏览器
        const response_result = await window.electronAPI.fetch(
          "http://local.adspower.net:50325/api/v1/user/create",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              name: unique_tag,
              group_id,
              user_proxy_config: {
                proxy_soft: "no_proxy",
              },
              fingerprint_config: {
                location: "block",
                language: ["zh-CN", "zh"],
                ua: "Mozilla/5.0 (Windows NT 10.0: Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63Safari/537.36",
              },
            }),
          }
        );
        // 打开浏览器
        if (!response_result.data.id) {
          ElMessage.error(response_result.msg);
          return;
        }
        await openBrowser(
          response_result,
          0,
          true,
          unique_tag,
          python_key + exact_key
        );
        return;
      }
      if (!is_new && ads_power_id) {
        await openBrowser(
          ads_power_id,
          0,
          false,
          unique_tag,
          python_key + exact_key
        );
        return;
      }
      ElMessage.error("您没有额度");
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    console.log("err");
  } finally {
    if (python_key === "a") {
      loadingA.value = false;
    }
    if (python_key === "b") {
      loadingB.value = false;
    }
  }
};
// 单列操作
const handleSingleBrowser = async (python_key, item) => {
  const { ads_power_id, unique_tag } = item;
  const exact_key = isWindows() ? "_win" : "";
  try {
    await openBrowser(
      ads_power_id,
      0,
      false,
      unique_tag,
      python_key + exact_key
    );
  } catch (err) {
    console.log("err");
  }
};

const handDelete = async () => {
  try {
    await handleDelAds(selectedItem.value.ads_power_id);
    const res = await user_delete({ xhs_user_id: selectedItem.value.id });
    if (res.code === 0) {
      ElMessage.success("删除账户成功");
      deleteShow.value = false;
      getList({ page_size: 10, page: 1 });
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    console.log(err);
  }
};

const handUpdate = async () => {
  const res = await user_update({ id: selectedItem.value.id, ...updateForm });
  if (res.code === 0) {
    ElMessage.success("编辑账户成功");
    editShow.value = false;
    getList({ page_size: 10, page: 1 });
  } else {
    ElMessage.error(res.msg);
  }
};
const handleRefresh = () => {
  getList({ page_size: 10, page: 1 });
};
const handleSizeChange = (val) => {
  page_size.value = val;
};
const handleCurrentChange = (val) => {
  page.value = val;
};
const isWindows = () => {
  return navigator.userAgent.indexOf("Win") !== -1;
};
const getList = async (params) => {
  try {
    const res = await xhs_list({
      page_size: page_size.value,
      page: page.value,
      ...params,
    });
    if (res.code === 0) {
      tableData.value = res.data.list;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    console.log("err");
  }
};
watch(
  [page_size, page],
  () => {
    getList();
  },
  {
    immediate: true,
  }
);
</script>
<style scoped lang="scss">
.btn_container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;

  .refreshBtn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #78d0ec63;
    color: #78d0ecf2;
    border-radius: 50%;
    margin-left: 10px;
    cursor: pointer;
  }
}

.container {
  width: 100%;
  height: 100%;
  padding: 50px;
  box-sizing: border-box;
}

.page_container {
  float: right;
  margin-top: 40px;
}

:deep(.el-table__header) {
  background-color: #f5f7fa !important;
}

:deep(.el-table tr) {
  background-color: rgba(0, 0, 0, 0);
}

:deep(.el-table th.el-table__cell) {
  background-color: rgba(0, 0, 0, 0);
}

.model-item {
  width: 90%;
}
</style>
